package com.designpattern.StrategyPattern.example2;

/**
 * @Author yue
 * @Date 2022-03-16
 * @Describe
 */

import java.util.HashMap;
import java.util.Map;

/**
 * 分享工厂（行为工厂）
 */
public class ShareFactory {

    // 定义策略枚举
    enum ShareType {
        SINGLE("single", "单商品"),
        MULTI("multi", "多商品"),
        ORDER("order", "下单");

        // 场景对应的编码
        private String code;
        // 业务场景描述
        private String desc;

        ShareType(String code, String desc) {
            this.code = code;
            this.desc = desc;
        }

        public String getCode() {
            return code;
        }
        // 省略 get set 方法
    }

    // 定义策略map缓存
    private static final Map<String, ShareStrategy> shareStrategies = new HashMap<>();

    // 添加到内存中，目的：通过 key 获得 value 实例
    static {
        shareStrategies.put("order", new OrderItemShare());
        shareStrategies.put("single", new SingleItemShare());
        shareStrategies.put("multi", new MultiItemShare());
    }

    /**
     * 获取指定策略
     *
     * @param type 行为类型
     * @return 行为实例
     */
    public static ShareStrategy getShareStrategy(String type) {
        if (type == null || type.isEmpty()) {
            throw new IllegalArgumentException("类型不应为空");
        }
        return shareStrategies.get(type);
    }

}
